using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Dare.Utilities.Data
{
    [AttributeUsage(AttributeTargets.Field)]
    public class DbEnumAttribute : Attribute
    {
        private static Dictionary<Enum, string> dictCacheNames;
        static DbEnumAttribute()
        {
            dictCacheNames = new Dictionary<Enum, string>(200);
        }

        private string name;
        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
            }
        }

        public DbEnumAttribute()
        {
        }

        public DbEnumAttribute(string name)
        {
            this.name = name;
        }

        public override string ToString()
        {
            return name;
        }

        public static string GetDbName(Enum enumSubitem)
        {
            if (dictCacheNames.ContainsKey(enumSubitem))
            {
                return dictCacheNames[enumSubitem];
            }
            else
            {
                string name = enumSubitem.ToString();
                FieldInfo fieldinfo = enumSubitem.GetType().GetField(name);
                object[] objs = fieldinfo.GetCustomAttributes(typeof(DbEnumAttribute), false);
                if (objs.Length > 0)
                {
                    name = ((DbEnumAttribute)objs[0]).Name;
                }

                dictCacheNames[enumSubitem] = name;
                return name;
            }
        }
    }
}
